package com.zx._12_算法.剑指offer._2022;

import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode.cn/problems/he-wei-sde-liang-ge-shu-zi-lcof/
 */
public class 和为s的两个数字 {

    /**
     * 1. 暴力破解
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum1(int[] nums, int target) {
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int n1 = nums[i];
            int n2 = target - n1;
            boolean is = false;
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == n2) {
                    is = true;
                    break;
                } else if (nums[j] > n2) {
                    break;
                }
            }
            if (is) {
                res[0] = n1;
                res[1] = n2;
                return res;
            }
        }
        return res;
    }

    public int[] twoSum(int[] nums, int target) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        int n1 = 0;
        int n2 = 0;
        for (int i = 0; i < nums.length; i++) {
            n1 = nums[i];
            n2 = target - n1;
            if (set.contains(n2)) {
                break;
            }
        }

        return new int[]{n1, n2};
    }
}
